import { Plugin } from "vite"
import fs from 'node:fs'
import dedent from 'dedent'
const mdRE = /\.md$/;

const getDescription = (str: string) => {
  // 按行分割，筛选出包含 '@Description:' 的行，然后截掉 '@Description:'
  return str.split('\r\n').find(i => i.includes('@Description:'))?.split('@Description:').at(-1)?.trim() ?? ''
}

export default function markdownPlugin(): Plugin {
  return {
    // 插件名称
    name: 'vite:markdown',

    transform(code, id, opt) {

      if (!mdRE.test(id)) return code;
      else {
        const hooksRE = /examples\/([\w-]+)\/index\.md$/
        const matched = id.match(hooksRE)

        if (matched) {
          const hookname = matched[1]
          const demoSnippet =
            dedent(
            `
              <script setup lang="ts">
              import Demo from "./demo.vue"
              console.log(Demo)
              </script>
              
              <el-card v-if="Demo.setup">
                <div class="demo-containers">
                    <demo/>
                </div>
              </el-card>
              <p v-else>暂无 Demo</p>
            `)
          const usageSnippet = fs.readFileSync(`docs/examples/${hookname}/demo.vue`).toString()

          // 从源码中截出 description
          const source = fs.readFileSync(`packages/core/${hookname}/index.ts`).toString()
          const descriptionSnippet = getDescription(source)
        
          return code.replace('__DESCRIPTION', descriptionSnippet).replace('__DEMO_SLOT', demoSnippet).replace('__USAGE_SLOT', usageSnippet)
        }

        return code
      }
    },
  }
}

